import {
	defineStore
} from 'pinia'
import {
	ref
} from 'vue'

export const useRankingStore = defineStore('ranking', () => {
	const nationalRanking = ref([])
	const friendsRanking = ref([])
	const loading = ref(false)
	const error = ref(null)

	// 统一请求方法
	const request = async (options) => {
		return new Promise((resolve, reject) => {
			uni.request({
				...options,
				success: (res) => resolve(res),
				fail: (err) => reject(err)
			})
		})
	}

	const fetchRankingData = async (type) => {
		loading.value = true
		error.value = null

		try {
			const res = await request({
				url: 'http://localhost:8080/api/ranking/list',
				method: 'GET',
				data: {
					type
				},
				header: {
					'Content-Type': 'application/json'
				}
			})

			if (!res) throw new Error('无响应数据')
			if (res.statusCode !== 200 || res.data.code !== 200) {
				throw new Error(res.data?.msg || '获取排行榜数据失败')
			}

			const formattedData = res.data.data.map((item, index) => ({
				rank: index + 1, // 使用索引+1作为排名
				name: item.name || '匿名用户',
				carbon: item.carbonAmount || 0,
				imageUrl: item.avatar || '/static/images/community-avter.jpg'
			}))

			if (type === 1) {
				nationalRanking.value = formattedData
			} else {
				friendsRanking.value = formattedData
			}
		} catch (err) {
			error.value = err.message
			console.error('请求出错:', err)
			uni.showToast({
				title: err.message || '网络请求失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}

	return {
		nationalRanking,
		friendsRanking,
		loading,
		error,
		fetchRankingData
	}
})